package controll;

import dao.UserDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/jsonUser")
public class JsonUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDao ud=new UserDao();
        List<User> users=ud.findAll();
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out=resp.getWriter();
        String[] keys={"bh","name","pwd","phone","img"};
       StringBuffer json=new StringBuffer("[");
       for (int i=0;i<users.size();i++){
           json.append("{");
           User u=users.get(i);
           Object[] values=u.toArray();
           for (int j=0;j<keys.length;j++){
               json.append("\""+keys[j]+"\":\""+values[j]+"\"");
               if (j<keys.length-1)
                   json.append(",");
           }
           json.append("}");
           if (i<users.size()-1)
               json.append(",");
       }
       json.append("]");
        out.write(json.toString());
       out.close();
    }
}
